﻿using DB;
using Models;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Elixi_AntdUi
{
    public partial class RegisterForm : AntdUI.Window
    {
        private readonly SqlSugarScope _db = SqlSugarHelper.Db;
        public string RegisteredUserName { get; private set; }
        public string RegisteredUserPsw { get; private set; }

        public RegisterForm()
        {
            InitializeComponent();
            // 初始化表单控件
            InitializeRegisterControls();
        }

        private void InitializeRegisterControls()
        {
            // 设置窗口属性
            this.Text = "用户注册";
            this.Size = new Size(350, 280);
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.StartPosition = FormStartPosition.CenterParent;
            this.MaximizeBox = false;

            // 创建并设置标签和文本框
            Label lblUserName = new Label { Text = "用户名:", Left = 30, Top = 30, Width = 70 };
            TextBox txtUserName = new TextBox { Left = 110, Top = 30, Width = 180 };

            Label lblPassword = new Label { Text = "密码:", Left = 30, Top = 70, Width = 70 };
            TextBox txtPassword = new TextBox { Left = 110, Top = 70, Width = 180, PasswordChar = '*' };

            Label lblConfirmPwd = new Label { Text = "确认密码:", Left = 30, Top = 110, Width = 70 };
            TextBox txtConfirmPwd = new TextBox { Left = 110, Top = 110, Width = 180, PasswordChar = '*' };

            // 用户编号显示（只读）
            Label lblUserCode = new Label { Text = "用户编号:", Left = 30, Top = 150, Width = 70 };
            TextBox txtUserCode = new TextBox
            {
                Left = 110,
                Top = 150,
                Width = 180,
                ReadOnly = true,
                BackColor = SystemColors.Control
            };

            // 预先生成用户编号
            try
            {
                string nextUserCode = GenerateNextUserCode();
                txtUserCode.Text = nextUserCode;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成用户编号失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            // 创建按钮
            Button btnRegister = new Button { Text = "注册", Left = 100, Top = 190, Width = 75 };
            Button btnCancel = new Button { Text = "取消", Left = 190, Top = 190, Width = 75 };

            // 注册按钮事件
            btnRegister.Click += (s, e) =>
            {
                string userName = txtUserName.Text.Trim();
                string password = txtPassword.Text;
                string confirmPwd = txtConfirmPwd.Text;
                string userCode = txtUserCode.Text.Trim();

                // 验证输入
                if (string.IsNullOrWhiteSpace(userName))
                {
                    MessageBox.Show("用户名不能为空", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtUserName.Focus();
                    return;
                }

                if (userName.Length < 3)
                {
                    MessageBox.Show("用户名至少需要3个字符", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtUserName.Focus();
                    return;
                }

                if (string.IsNullOrWhiteSpace(password))
                {
                    MessageBox.Show("密码不能为空", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtPassword.Focus();
                    return;
                }

                if (password.Length < 6)
                {
                    MessageBox.Show("密码至少需要6个字符", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtPassword.Focus();
                    return;
                }

                if (password != confirmPwd)
                {
                    MessageBox.Show("两次输入的密码不一致", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtConfirmPwd.Focus();
                    return;
                }

                if (string.IsNullOrWhiteSpace(userCode))
                {
                    MessageBox.Show("用户编号生成失败，请重试", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                try
                {
                    // 检查用户名是否已存在
                    bool userExists = _db.Queryable<Tb_UsersInfo>()
                        .Any(u => u.UserName == userName);

                    if (userExists)
                    {
                        MessageBox.Show("该用户名已被注册", "注册失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtUserName.Focus();
                        return;
                    }

                    // 检查用户编号是否已存在（防止并发问题）
                    bool codeExists = _db.Queryable<Tb_UsersInfo>()
                        .Any(u => u.UserCode == userCode);

                    if (codeExists)
                    {
                        // 重新生成用户编号
                        txtUserCode.Text = GenerateNextUserCode();
                        MessageBox.Show("用户编号已被使用，已自动生成新编号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    // 创建新用户
                    Tb_UsersInfo newUser = new Tb_UsersInfo
                    {
                        GUID = Guid.NewGuid().ToString(),
                        UserName = userName,
                        UserPassWord = Md5Encrypt(password), // 注意：实际应用中应该加密存储密码
                        UserCode = userCode,    // 添加用户编号

                    };

                    // 保存到数据库
                    _db.Insertable(newUser).ExecuteCommand();
                    //保存配置到config
                    //AppConfig.UpdateCurrentUser(config.CurrentUser.UserName, config.CurrentUser.UserGuid);
                    AppConfig.UpdateCurrentUser(newUser.UserName, newUser.GUID, newUser.UserPassWord );
                    RegisteredUserName = userName;
                    RegisteredUserPsw = password;
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"注册失败: {ex.Message}", "数据库错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            };

            // 取消按钮事件
            btnCancel.Click += (s, e) =>
            {
                this.DialogResult = DialogResult.Cancel;
                this.Close();
            };

            // 将控件添加到窗口
            this.Controls.AddRange(new Control[] { lblUserName, txtUserName, lblPassword, txtPassword,
                                             lblConfirmPwd, txtConfirmPwd, lblUserCode, txtUserCode,
                                             btnRegister, btnCancel });
        }
        /// <summary>
        /// 计算字符串的MD5加密结果（32位小写）
        /// </summary>
        /// <param name="input">待加密的字符串</param>
        /// <returns>MD5加密后的32位十六进制字符串</returns>
        public static string Md5Encrypt(string input)
        {
            // 处理空输入（视为空字符串）
            input ??= string.Empty;

            // 创建MD5实例
            using (MD5 md5 = MD5.Create())
            {
                // 1. 将字符串转为UTF8字节数组
                byte[] inputBytes = Encoding.UTF8.GetBytes(input);

                // 2. 计算MD5哈希值（得到16字节的哈希结果）
                byte[] hashBytes = md5.ComputeHash(inputBytes);

                // 3. 将哈希字节数组转为32位十六进制字符串
                StringBuilder sb = new StringBuilder();
                foreach (byte b in hashBytes)
                {
                    // 每个字节转为2位十六进制（x2表示小写，X2表示大写）
                    sb.Append(b.ToString("x2"));
                }
                return sb.ToString();
            }
        }
        /// <summary>
        /// 生成下一个用户编号（取数据库中最大UserCode加1）
        /// </summary>
        private string GenerateNextUserCode()
        {
            try
            {
                // 查询数据库中最大的UserCode
                var maxUserCode = _db.Queryable<Tb_UsersInfo>()
                                     .Max(u => u.UserCode);

                if (string.IsNullOrWhiteSpace(maxUserCode))
                {
                    // 如果没有用户，从1开始
                    return "1";
                }

                // 尝试将最大UserCode转换为数字
                if (int.TryParse(maxUserCode, out int codeNumber))
                {
                    // 加1后转换回字符串
                    return (codeNumber + 1).ToString();
                }
                else
                {
                    // 如果UserCode不是数字格式，尝试提取数字部分
                    string numericPart = new string(maxUserCode.Where(char.IsDigit).ToArray());
                    if (int.TryParse(numericPart, out int num))
                    {
                        // 保留原始格式，只增加数字部分
                        string nonNumericPart = new string(maxUserCode.Where(c => !char.IsDigit(c)).ToArray());
                        return nonNumericPart + (num + 1).ToString();
                    }
                    else
                    {
                        // 如果无法解析数字，使用当前时间戳作为备用方案
                        return DateTime.Now.Ticks.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"生成用户编号时出错: {ex.Message}");
            }
        }

        private void RegisterForm_Load(object sender, EventArgs e)
        {

        }
    }
}
